package com.hns.can.master.service;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.hns.can.master.entity.BaseDrvInfoEntity;
import com.hns.frame.dao.SqlMapDao;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hns.can.base.entity.SysUserEntity;
import com.hns.can.common.constants.GlobalConst;
import com.hns.can.common.entity.BaseEntity;
import com.hns.can.common.formula.FillCodeDscValue;
import com.hns.can.common.formula.FillParamsVo;
import com.hns.can.master.entity.BaseCarInfoEntity;
import com.hns.can.master.entity.BaseEqmtInfoEntity;
import com.hns.can.master.vo.CarPostDataVo;
import com.hns.frame.enumrate.EnabledSt;
import com.hns.frame.mybatis.Pagination;
import com.hns.frame.service.CommonService;
import com.hns.tool.pub.PubUtil;
import com.hns.tool.pub.UtilString;

/**
 * 车辆信息维护业务类
 * @author:lan
 * @email:763836737@qq.com
 * @version Revision 2.0.0
 */
@Service
public class BaseCarInfoService extends CommonService {
    
	/**
	 * 填充代码描述
	 */
    @Autowired
    private FillCodeDscValue codeDscValue;
    @Autowired
    private SqlMapDao sqlMaoDao;
    
    /**
     * 添加一个车辆
     * @param entity
     * @param user
     * @author:lan
     * @email:763836737@qq.com
     */
    @Transactional
    @CacheEvict(value=GlobalConst.CACHE_KEY_BASE_CAR_INFO, key="#user.getCorpId()")
    public synchronized void addCarInfo(BaseCarInfoEntity entity, SysUserEntity user) {
    	
        // 补充实体的其他信息
        entity.setCarId(UtilString.getUUID());
        entity.setEnabledSt(EnabledSt.ENABLE.getFlag()); // 启用状态
        entity.setCrtTime(new Date());
        entity.setCrtUser(user.getAcctName());
        entity.setUpdateTime(new Date());
        entity.setUpdateUser(user.getAcctName());
        
        // 后台校验
        checkAddAndUpdate(entity);
        
        commonEntityDao.save(entity);
    }
    
   /**
    * 根据BaseCarInfoEntity获取车辆列表
    * @param entity
    * @return
    * @author:lan
    * @email:763836737@qq.com
    */
    @SuppressWarnings("unchecked")
    public List<BaseCarInfoEntity> getBaseCarInfoList(BaseCarInfoEntity entity) {
        List<BaseCarInfoEntity> list = PubUtil.convertListMapToObject(
            this.sqlMapDao.selectList("baseCarInfo.getBaseCarInfoList", entity), BaseCarInfoEntity.class);
        return list;
    }
    
    /**
     * <!-- 设备关联车辆    过滤已关联车辆 -->
     * @param entity
     * @return
     * @author:lan
     * @email:763836737@qq.com
     */
    @SuppressWarnings("unchecked")
    public List<BaseCarInfoEntity> getBaseCarInfoListForEq(BaseCarInfoEntity entity) {
        List<BaseCarInfoEntity> list = PubUtil.convertListMapToObject(
            this.sqlMapDao.selectList("baseCarInfo.getBaseCarInfoListForEq", entity), BaseCarInfoEntity.class);
        return list;
    }
    
   /**
    * 得到车辆page对象
    * @param dataVo
    * @return
    * @throws Exception
    * @author:lan
    * @email:763836737@qq.com
    */
    @Transactional
    public Pagination searchCarInfoPage(CarPostDataVo dataVo) throws Exception {
        Pagination page = this.myBatisPage("baseCarInfo.getCarInfoCnt", "baseCarInfo.getCarInfoList", dataVo,BaseCarInfoEntity.class);
        Map<String,String> map = new HashMap<String,String>();
        map.put("organName", GlobalConst.DEFAULT_CACHE_VALUE);   
        FillParamsVo vo = new FillParamsVo("organId", map);
        codeDscValue.fillInfoValue(page.getData(), new String[] {GlobalConst.CACHE_KEY_BASE_ORGAN}, vo);
        return page;
    }
    
    /**
     * 得到车辆信息list对象
     * @param dataVo
     * @return
     * @throws Exception
     * @author:lan
     * @email:763836737@qq.com
     */
    @SuppressWarnings({"unchecked"})
    @Transactional
    public List<BaseEntity> getCarInfoList(CarPostDataVo dataVo) throws Exception {
    	List<BaseEntity> list = PubUtil.convertListMapToObject(this.sqlMapDao.selectList("baseCarInfo.getCarInfoList", dataVo), BaseCarInfoEntity.class);
	    Map<String,String> map = new HashMap<String,String>();
        map.put("organName", GlobalConst.DEFAULT_CACHE_VALUE);   
        FillParamsVo vo = new FillParamsVo("organId", map);
        codeDscValue.fillInfoValue(list, new String[] {GlobalConst.CACHE_KEY_BASE_ORGAN},vo);
        Map<String,String> mapTmp = new HashMap<String,String>();
        mapTmp.put("carType", "CAT00000");
        mapTmp.put("flOilType", "FUT00000");
        codeDscValue.fillCodeDscValue(list, mapTmp);
        return list;
    }
   /**
    * 根据车辆id求车辆信息
    * @param carId
    * @return
    * @throws Exception
    * @author:lan
    * @email:763836737@qq.com
    */
    @SuppressWarnings({"unchecked"})
    public BaseEntity getCarInfoByCarId(String carId) throws Exception {
        List<BaseEntity> list = PubUtil.convertListMapToObject(
            this.sqlMapDao.selectList("baseCarInfo.getCarInfoByCarId", carId), BaseCarInfoEntity.class);
        Map<String,String> map = new HashMap<String,String>();
        map.put("corpName", GlobalConst.DEFAULT_CACHE_VALUE);   
        FillParamsVo vo1 = new FillParamsVo("corpId", map);
        Map<String,String> map2 = new HashMap<String,String>();
        map2.put("organName", GlobalConst.DEFAULT_CACHE_VALUE);
        FillParamsVo vo2 = new FillParamsVo("organId", map2);
        codeDscValue.fillInfoValue(list, new String[] {GlobalConst.CACHE_KEY_SYS_CORP, GlobalConst.CACHE_KEY_BASE_ORGAN},vo1, vo2);
        return list.get(0);
    }
    
   /**
    * 更新一个车辆的信息
    * @param user
    * @param entity
    * @author:lan
    * @email:763836737@qq.com
    */
    @Transactional
    @CacheEvict(value=GlobalConst.CACHE_KEY_BASE_CAR_INFO, key="#user.getCorpId()")
    public void uptCarInfo(SysUserEntity user, BaseCarInfoEntity entity) {
        BaseCarInfoEntity tmpEntity = commonEntityDao.find(entity.getCarId(), BaseCarInfoEntity.class);
        entity.setEnabledSt(tmpEntity.getEnabledSt()); // 启用状态
        entity.setCrtTime(tmpEntity.getCrtTime());
        entity.setCrtUser(tmpEntity.getCrtUser());
        entity.setCarSt(tmpEntity.getCarSt());
        entity.setUpdateTime(new Date());
        entity.setUpdateUser(user.getAcctName());
        // 后台校验
        checkAddAndUpdate(entity);
        // 关联更新的操作
        // 车辆信息中更改了车辆所属机构，设备信息表中也要更新所属机构。
        if (!entity.getOrganId().equals(tmpEntity.getOrganId())) {
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("rltvCarId", entity.getCarId());
            List<BaseEqmtInfoEntity> list = commonEntityDao.findByParamsIgnoreNullValue(BaseEqmtInfoEntity.class, params);
            if (PubUtil.isNotEmpty(list)) {
                BaseEqmtInfoEntity eqmt = list.get(0);
                eqmt.setOrganId(entity.getOrganId());
                commonEntityDao.update(eqmt);
            }
        }
        commonEntityDao.update(entity);
    }
   /**
    * 删除一个车辆
    * @param user
    * @param carIds
    * @author:lan
    * @email:763836737@qq.com
    */
    @Transactional
    @CacheEvict(value=GlobalConst.CACHE_KEY_BASE_CAR_INFO, key="#user.getCorpId()")
    public void delCarInfo(SysUserEntity user, String[] carIds) {
        for (String carId : carIds) {
            BaseCarInfoEntity entity = commonEntityDao.find(carId, BaseCarInfoEntity.class);
            entity.setEnabledSt(EnabledSt.DISABLE.getFlag());
            entity.setUpdateTime(new Date());
            entity.setUpdateUser(user.getAcctName());
            // 关联删除的操作
            // 对应解除绑定在该车辆的设备
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("rltvCarId", entity.getCarId());
            List<BaseEqmtInfoEntity> list = commonEntityDao.findByParamsIgnoreNullValue(BaseEqmtInfoEntity.class, params);
            if (PubUtil.isNotEmpty(list)) {
                BaseEqmtInfoEntity eqmt = list.get(0);
                eqmt.setRltvCarId(null);
                commonEntityDao.update(eqmt);
            }
            commonEntityDao.update(entity);
        }
    }
    /**
     * 查询是否绑定
     * @param carIds
     * @author:xy
     * @email:763836737@qq.com
     */
    @Transactional
    public int findBangInfo(String[] carIds) {
        CarPostDataVo dataVo=new CarPostDataVo();
        String carID="";
        for (String carId : carIds) {
            carID+="'"+carId+"',";
        }
        dataVo.setQorganId(carID.substring(0,carID.length()-1));
       int count=(Integer) sqlMapDao.selectOne("baseCarInfo.getBangInfo", dataVo);
        return  count;
    }

    /**
   * 根据机构ids获取对应的车辆ID列表
   * @param orgIdList
   * @return
   * @author:lan
   * @email:763836737@qq.com
   */
    @SuppressWarnings("unchecked")
    public List<String> getBaseCarInfoListByOrgIdList(List<String> orgIdList) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("orgIdList", orgIdList);
        List<BaseCarInfoEntity> baseCarInfolist = PubUtil.convertListMapToObject(
            this.sqlMapDao.selectList("baseCarInfo.getBaseCarInfoListByOrgIdList", map), BaseCarInfoEntity.class);
        List<String> list = new ArrayList<String>();
        if (PubUtil.isEmpty(baseCarInfolist)) {
            return null;
        } else {
            for (BaseCarInfoEntity entity : baseCarInfolist) {
                list.add(entity.getCarId());
            }
        }
        return list;
    }
    
    /**
     * 检查添加和更新是否符合条件，后台校验
     * @param entity
     * @author:lan
     * @email:763836737@qq.com
     */
    private void checkAddAndUpdate(BaseCarInfoEntity entity) {
        // -- 车牌号 licPltNo
        if (PubUtil.isNotEmpty(entity.getLicPltNo())) {
            this.check("baseCarInfo.checkLicPltNo",entity,"您输入的车牌号已经存在！");
        }
        // -- 车辆内部编号 carInCd
        if (PubUtil.isNotEmpty(entity.getCarInCd())) {
            this.check("baseCarInfo.checkCarInCd",entity,"您输入的车辆编号已经存在！");
        }
        // -- 营运证号 operCertiNo
        if (PubUtil.isNotEmpty(entity.getOperCertiNo())) {
            this.check("baseCarInfo.checkOperCertiNo",entity,"您输入的营运证号已经存在！");
        }
        // -- 底盘编号 chassisCd
        if (PubUtil.isNotEmpty(entity.getChassisCd())) {
            this.check("baseCarInfo.checkChassisCd",entity,"您输入的底盘编号已经存在！");
        }
        // -- 发动机号 engiNo
        if (PubUtil.isNotEmpty(entity.getEngiNo())) {
            this.check("baseCarInfo.checkEngiNo",entity,"您输入的发动机号已经存在！");
        }
        // -- 车 架 号 frameNo
        if (PubUtil.isNotEmpty(entity.getFrameNo())) {
            this.check("baseCarInfo.checkFrameNo",entity,"您输入的车 架 号已经存在！");
        }
    }

    /**
     * 将数据存到数据库中
     * @param list
     * @param user
     * @param organId
     * @return
     * @throws Exception
     */
    @Transactional(rollbackFor=Exception.class)
    @CacheEvict(value=GlobalConst.CACHE_KEY_BASE_CAR_INFO, key="#user.getCorpId()")
    public String saveCarInfoToDB(List<BaseCarInfoEntity> list, SysUserEntity user, String organId) throws Exception{
        int count = 6;
        successCount = 0;
        String msgs = "";
        String allMsg= "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //通过机构ID找到企业ID
        Map<String,Object> mapId = new HashMap<String,Object>();
        mapId.put("organId", organId);
        Map<String,String> map = (Map<String, String>) sqlMaoDao.selectOne("baseDrvInfo.searchCorp",mapId);
        String corpId = map.get("CORP_ID");
        mapId.put("corpId",corpId);
        for(BaseCarInfoEntity entity:list){
            if(PubUtil.isEmpty(entity.getLicPltNo())){
                msgs = "";
                msgs = "第"+count+"行的车牌号不能为空。<br/> ";
                allMsg = allMsg + msgs;
                count++;
                continue;
            }
            if(PubUtil.isEmpty(entity.getFlOilType())){
                msgs = "";
                msgs = "第"+count+"行的车辆燃油类型不能为空或车辆燃油类型不存在。<br/> ";
                allMsg = allMsg + msgs;
                count++;
                continue;
            }
            if(PubUtil.isEmpty(entity.getCarType())){
                msgs = "";
                msgs = "第"+count+"行的车辆类型不能为空或车辆类型不存在。<br/> ";
                allMsg = allMsg + msgs;
                count++;
                continue;
            }
            if(PubUtil.isEmpty(entity.getCarModel())){
                msgs = "";
                msgs = "第"+count+"行的车辆型号不能为空。<br/> ";
                allMsg = allMsg + msgs;
                count++;
                continue;
            }
            count++;
            mapId.put("licPltNo",entity.getLicPltNo());
            List<BaseCarInfoEntity> carInfo = commonEntityDao.findByParamsIgnoreNullValue(BaseCarInfoEntity.class,mapId);

            if(carInfo.size() > 0){
                BaseCarInfoEntity dbEntity = carInfo.get(0);
                //车辆编号
                dbEntity.setCarInCd(entity.getCarInCd());
                //车辆类型
                dbEntity.setCarType(entity.getCarType());
                //车辆型号
                dbEntity.setCarModel(entity.getCarModel());
                //燃油类型
                dbEntity.setFlOilType(entity.getFlOilType());
                //生产厂家
                dbEntity.setProduceFacty(entity.getProduceFacty());
                //购置日期
                dbEntity.setPrchDate(entity.getPrchDate());
                //车架号
                dbEntity.setFrameNo(entity.getFrameNo());
                //发动机厂家
                dbEntity.setEngiFacty(entity.getEngiFacty());
                //发动机型号
                dbEntity.setEngiModel(entity.getEngiModel());
                //启用
                dbEntity.setEnabledSt(EnabledSt.ENABLE.getFlag());
                //状态
                dbEntity.setCarSt("0");
                //修改时间
                dbEntity.setUpdateTime(new Date());
                //修改人
                dbEntity.setUpdateUser(user.getAcctName());
                //保存
                commonEntityDao.update(dbEntity);
            }else{
                entity.setCarId(UtilString.getUUID());
                entity.setCrtUser(user.getAcctName());
                entity.setCrtTime(new Date());
                entity.setEnabledSt(EnabledSt.ENABLE.getFlag());
                entity.setCorpId(corpId);
                entity.setOrganId(organId);
                //状态
                entity.setCarSt("0");
                commonEntityDao.save(entity);
            }
            successCount++;
        }
        return allMsg;
    }

    private  int successCount;
    public int getSuccessCount() {
        return successCount;
    }
}
